<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    style="min-width: 1000px"
    scroll
    :max-height="600"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="合同名称" prop="contractName">
        <el-input v-model="formData.contractName" placeholder="请输入合同名称" />
      </el-form-item>
      <el-form-item label="合同编号" prop="contractNo">
        <el-input v-model="formData.contractNo" placeholder="请输入合同编号" />
      </el-form-item>
      <el-form-item label="乙方" prop="partyB">
        <!--        <el-select v-model="formData.partyB" placeholder="请选择乙方名称（供应商）">-->
        <!--          <el-option label="请选择字典生成" value="" />-->
        <!--        </el-select>-->
        <el-select
          v-model="formData.partyB"
          clearable
          filterable
          placeholder="请选择供应商"
          class="!w-1/1"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <template class="flex">
        <el-form-item label="签订时间" prop="signingDate">
          <el-date-picker
            v-model="formData.signingDate"
            type="date"
            value-format="x"
            placeholder="选择签订时间"
          />
        </el-form-item>
        <el-form-item label="终止日期" prop="expirationDate">
          <el-date-picker
            v-model="formData.expirationDate"
            type="date"
            value-format="x"
            placeholder="选择终止日期"
          />
        </el-form-item>
      </template>
      <el-form-item label="生效日期" prop="effectiveDate">
        <el-date-picker
          v-model="formData.effectiveDate"
          type="date"
          value-format="x"
          placeholder="选择生效日期"
        />
      </el-form-item>
      <el-form-item label="合同责任人" prop="contractPerson">
        <el-input v-model="formData.contractPerson" placeholder="请输入合同责任人" />
      </el-form-item>
      <el-form-item label="摘要内容" prop="contractSummary">
        <el-input v-model="formData.contractSummary" placeholder="请输入摘要内容" type="textarea" />
      </el-form-item>
      <ContentWrap>
        <el-tabs class="-mt-15px -mb-10px" v-model="subTabsName">
          <el-tab-pane label="物料价格关联区块" name="item">
            <MarketContractItemForm ref="itemFormRef" :items="formData.items" />
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
      <el-form-item label="文件" prop="contractFile">
        <UploadFile v-model="formData.contractFile" :fileType="['pdf']" />
      </el-form-item>
      <el-form-item label="版本备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入版本备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { MarketContractApi, MarketContractVO } from '@/api/erp/marketcontract'
import { SupplierApi, SupplierVO } from '@/api/erp/purchase/supplier'
import MarketContractItemForm from './components/MarketContractItemForm.vue'

/** 市场管理合同信息 表单 */
defineOptions({ name: 'MarketContractForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const supplierList = ref<SupplierVO[]>([]) // 供应商列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  partyB: undefined,
  id: undefined,
  contractName: undefined,
  contractNo: undefined,
  partyB: undefined,
  signingDate: undefined,
  expirationDate: undefined,
  effectiveDate: undefined,
  contractSummary: undefined,
  contractPerson: undefined,
  contractFile: undefined,
  items: [],
  remark: undefined
})
const formRules = reactive({
  contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  contractNo: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
  partyB: [{ required: true, message: '乙方名称（供应商）不能为空', trigger: 'change' }],
  signingDate: [{ required: true, message: '签订时间不能为空', trigger: 'blur' }],
  expirationDate: [{ required: true, message: '终止日期不能为空', trigger: 'blur' }],
  effectiveDate: [{ required: true, message: '生效日期不能为空', trigger: 'blur' }],
  contractPerson: [{ required: true, message: '合同责任人不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const subTabsName = ref('item')
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MarketContractApi.getMarketContract(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载供应商列表
  supplierList.value = await SupplierApi.getSupplierSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MarketContractVO
    if (formType.value === 'create') {
      await MarketContractApi.createMarketContract(data)
      message.success(t('common.createSuccess'))
    } else {
      await MarketContractApi.updateMarketContract(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    contractName: undefined,
    contractNo: undefined,
    partyB: undefined,
    signingDate: undefined,
    expirationDate: undefined,
    effectiveDate: undefined,
    contractSummary: undefined,
    contractPerson: undefined,
    contractFile: undefined,
    items: [],
    remark: undefined
  }
  formRef.value?.resetFields()
}
</script>
